﻿using System;
using System.Linq;
using System.Web.Services;
using StampController.BL;
using StampController.BL.Models;
using StampController.Helpers;

namespace StampController.Pages
{
    public partial class AuthorizerForm : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                var user = SessionUtils.Get<UsersModel>("USER");
                var users = new UsersImpl().GetUserList().Where(x => x.UserID != user.UserID).ToList();
                users.Insert(0, new UsersModel { UserID = null, Name = "-- Select an authorized person --" });
                ddlAuthorizedPerson.DataSource = users;
                ddlAuthorizedPerson.DataValueField = "UserID";
                ddlAuthorizedPerson.DataTextField = "Name";
                ddlAuthorizedPerson.DataBind();
            }
        }

        [WebMethod]
        public static bool SaveAuthorized(AuthorizedHistoryModel authorized)
        {
            var user = SessionUtils.Get<UsersModel>("USER");
            if (user == null)
            {
                return false;
            }
            var im = new AuthorizedHistoryImpl();
            authorized.AuthorizedBy = user.UserID;
            authorized.CreatedDate = DateTime.Now;
            authorized.CreatedBy = user.UserID;
            authorized.Active = true;
            var result = im.SaveAuthorized(authorized);
            if (result)
            {
                var delegateItem = im.GetAuthorized(authorized.ID);
                return MailHelper.Send(delegateItem.DelegateMail, delegateItem);
            }

            return false;
        }
    }
}